package org.jdns.jfreechess.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

import java.util.logging.Logger;

import javax.inject.Inject;

import org.jdns.jfreechess.timeseal.TimesealedMessage;

import com.google.inject.Provider;

public class TimesealedMessageHandler extends
    ChannelInboundMessageHandlerAdapter<TimesealedMessage> {
  private final Logger log;
  private final Provider<User> userProvider;
  private final Provider<CommandMethod> userCommandProvider;
  private final Provider<String> commandNameProvider;

  @Inject
  public TimesealedMessageHandler(Logger log, Provider<User> userProvider,
      @UserCommand Provider<CommandMethod> userCommand,
      @UserCommand Provider<String> commandNameProvider) {
    this.log = log;
    this.userProvider = userProvider;
    this.userCommandProvider = userCommand;
    this.commandNameProvider = commandNameProvider;
  }

  @Override
  public void messageReceived(ChannelHandlerContext ctx, TimesealedMessage msg) throws Exception {
    log.info("Received: " + msg);
    Object result = userCommandProvider.get().invoke();
    if (result instanceof String) {
      ctx.write(result);
    }

    String commandName = commandNameProvider.get();
    if (!commandName.startsWith("$$")) {
      userProvider.get().resetLastCommandTime();
    }

    //
    // System.out.println(String.format("[%s]: %s", userProvider.get(), msg));
    // List<String> params =
    // Lists.newArrayList(Splitter.on(Pattern.compile("\\s")).trimResults().limit(3)
    // .split(msg.getMessage()));
    // if ("tell".equals(params.get(0)) || "$tell".equals(params.get(0))) {
    // String whom = params.get(1).replace("!", "");
    // String what = params.get(2);
    // server.getUser(whom).getChannel()
    // .write(String.format("\n%s tells you: %s\nfics%% ", userProvider.get().getName(), what));
    // ctx.channel().write("(told " + whom + ")");
    // } else {
    // ctx.channel().write("unknown command: " + params.get(0));
    // }
    //
    // ctx.channel().write("\nfics% ");
  }
}
